package net.sf.window.scope;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.SessionScope;

public class WindowScope extends SessionScope 
{
	public static final String WINDOW_SCOPE_NAME = "x-window-id";
	
	private static final String REQ_ATTR_NAME = "org.springframework.web.context.request.RequestContextListener.REQUEST_ATTRIBUTES";
	private static final String WINDOW_SCOPE_NAME_DILIMITER = "-";
	
	@SuppressWarnings("rawtypes")
	@Override
	public Object get(String name, ObjectFactory objectFactory) 
	{
		return super.get(getUniqueBeanNameForWindow(name), objectFactory);
	}
	@Override
	public Object remove(String name) 
	{
		return super.remove(getUniqueBeanNameForWindow(name));
	}
	private String getUniqueBeanNameForWindow(String name)
	{
		StringBuilder uniqueName = new StringBuilder(name);
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) 
														RequestContextHolder
														.currentRequestAttributes()
														.getAttribute(REQ_ATTR_NAME, 0);
		String windowId = getWindowIdFromHeaderOrParameter(requestAttributes.getRequest());
		if (windowId != null)
			return uniqueName.append(WINDOW_SCOPE_NAME_DILIMITER).append(windowId).toString();
		else
			return name;
	}
	private String getWindowIdFromHeaderOrParameter(HttpServletRequest request) 
	{
		String windowId = null;
		windowId = request.getHeader(WINDOW_SCOPE_NAME);
		if (windowId == null)
			windowId = String.valueOf(request.getParameter(WINDOW_SCOPE_NAME));
		return windowId;
	}
}
